import React, { Component } from 'react'
import { View, Alert } from 'react-native'
import { API, API_GENERATE } from '../config/api';
import HTTP from '../utils/http';
import Barcode from 'react-native-smart-barcode'
import TimerEnhance from 'react-native-smart-timer-enhance'

class BarcodeScan extends Component {

	// 构造
	constructor(props) {
		super(props);
		// 初始状态
		this.state = {
			viewAppear: false,
		};
	}

	render () {
		return (
			<View style={{ flex: 1, backgroundColor: 'black', }}>
				{this.state.viewAppear ? <Barcode style={{ flex: 1, }}
					ref={component => this._barCode = component}
					onBarCodeRead={this._onBarCodeRead} /> : null}
			</View>
		)
	}

	componentDidMount () {
		// let viewAppearCallBack = (event) => {
		this.setTimeout(() => {
			this.setState({
				viewAppear: true,
			})
		}, 255)

		// }
		this._listeners = [
			// this.props.navigation.navigationContext.addListener('didfocus', viewAppearCallBack)
			// DeviceEventEmitter.addListener('ChangeUI',
			// 	//接收到前一页发送的通知，刷新数据，刷新UI
			// 	viewAppearCallBack
			// )
		]

	}

	componentWillUnmount () {
		//this._listeners && this._listeners.forEach(listener => listener.remove());
	}

	_onBarCodeRead = (e) => {
		console.log(`e.nativeEvent.data.type = ${e.nativeEvent.data.type}, e.nativeEvent.data.code = ${e.nativeEvent.data.code}`);
		this.code = e.nativeEvent.data.code;
		this._stopScan();
		let { callback } = this.props.navigation.state.params
		if (e && callback) {
			console.log('data', e)
			this.props.navigation.state.params.callback(e);
			this.props.navigation.goBack();
			return
		}
		Alert.alert(e.nativeEvent.data.type, JSON.stringify(e.nativeEvent.data), [
			{ text: 'OK', onPress: () => this._startScan() },
		])
	}

	async _startScan (e) {
		const params = {
			isOcr: 1,
			ocrType: 'QR_INVOICE',
			code: this.code
		}

		const ocrInfo = await HTTP.POST(API_GENERATE(API.IMG_UPLOAD), params);
		let pageName = 'EnterpriseCreatePage';
		const { navigate, state } = this.props.navigation;
		if (state && state.params && state.params.pageName) {
			pageName = state.params.pageName;
		}

		if (ocrInfo) {
			navigate(this.pageName, { ocrInfo: ocrInfo });
		}
		//this._barCode.startScan();
	}

	_stopScan = (e) => {
		this._barCode.stopScan()
	}

}

export default TimerEnhance(BarcodeScan)
